package ug.co.icom.kyazze.healthticket;

import java.util.ArrayList;

import de.keyboardsurfer.android.widget.crouton.ConnectionDetector;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import ug.co.icom.kyazze.healthticket.data.MinUser;
import ug.co.icom.kyazze.healthticket.mongoHQ.MongoHQConnectionSearch;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class SearchResultsActivity extends Activity {

	private TextView txtQuery;
	private ArrayList<MinUser> connections = new ArrayList<MinUser>();
	private ListView lv;
	private MinUser[] connectionsArray;
	// Connection detector
	ConnectionDetector cd;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchactivity_layout);

		// get the action bar
		ActionBar actionBar = getActionBar();

		// Enabling Back navigation on Action Bar icon
		actionBar.setDisplayHomeAsUpEnabled(true);

		txtQuery = (TextView) findViewById(R.id.textView2);
		lv = (ListView) findViewById(R.id.listView1);	
		
		cd = new ConnectionDetector(getApplicationContext());
		
		// Check if Internet present
				if (!cd.isConnectingToInternet()) {
					// Internet Connection is not present
					Crouton.makeText(this,
							"No Active Internet Connection",
							Style.ALERT).show();
					
				//	return;
				}else{
					handleIntent(getIntent());
				}
		

		
	}

	@Override
	protected void onNewIntent(Intent intent) {
		//setIntent(intent);
		//handleIntent(intent);
	}


	/**
	 * Handling intent data
	 */
	private void handleIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);

			/**
			 * Use this query to display search results like 
			 * 1. Getting the data from SQLite and showing in listview 
			 * 2. Making webrequest and displaying the data 
			 * For now we just display the query only
			 */
			txtQuery.setText("Person To Search: " + query);

			try
			{
				MongoHQConnectionSearch mcs = new MongoHQConnectionSearch();
				connections = mcs.execute(query).get();

				connectionsArray = createMinUserArrayFromArrayCol(connections);
				lv.setAdapter(new SRAdapter(SearchResultsActivity.this,
						android.R.layout.simple_list_item_1, R.id.textView1, connectionsArray));

			}
			catch(Exception e)
			{
				AlertDialog.Builder builder = new AlertDialog.Builder(SearchResultsActivity.this);
				builder.setMessage("An Error Occured! Please Try Again");
				builder.setCancelable(true);
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();						
					}
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
		}

	}

	private MinUser[] createMinUserArrayFromArrayCol(
			ArrayList<MinUser> connections) {
		MinUser[] toReturn = new MinUser[connections.size()];

		int i = 0;
		for(MinUser mu: connections)
		{
			toReturn[i] = mu;
			i++;
		}

		return toReturn;
	}

	@SuppressWarnings("deprecation")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent upIntent = new Intent(this, SearchResultsActivity.class);
			if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
				// This activity is not part of the application's task, so
				// create a new task
				// with a synthesized back stack.
				TaskStackBuilder
				.from(this)
				.addNextIntent(new Intent(this, MainActivity.class))
				.addNextIntent(upIntent).startActivities();
				finish();
			} else {
				// This activity is part of the application's task, so simply
				// navigate up to the hierarchical parent activity.
				NavUtils.navigateUpTo(this, upIntent);
			}
			return true;
		}
		return false;
	}
	
	@Override
	protected void onPause() {
		connections.clear();
		super.onPause();
	}

	public void myClickHandler(View v) 
	{
		try
		{
			Button button = (Button)v;
			MinUser user = (MinUser) button.getTag();
			Intent i = new Intent(SearchResultsActivity.this, RequestConnectionActivity.class);
			i.putExtra("user", user);
            startActivity(i);
		}
		catch(Exception e)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(SearchResultsActivity.this);
			builder.setMessage("An Error Occured! Please Try Again");
			builder.setCancelable(true);
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();						
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
	
}
